package io.openkunlun.javadsl.client;

import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import io.openkunlun.javadsl.serialization.DaprSerializer;
import io.openkunlun.javadsl.v1.DaprCommonProtos;
import io.openkunlun.javadsl.v1.DaprProtos;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

public final class SetStateAction<T> implements DaprAction<Empty> {

    private String storeName;
    private List<StateItem<Object>> states;
    private DaprSerializer daprSerializer;

    /**
     * @param daprClient
     * @return
     */
    @Override
    public Empty invoke(DaprClient daprClient) throws Exception {
        List<io.openkunlun.javadsl.v1.DaprCommonProtos.StateItem> items = states.stream().map(it -> {
            ByteString value;
            try {
                value = ByteString.copyFrom(daprSerializer.serialize(it.getValue()));
            } catch (IOException e) {
                e.printStackTrace();
                value = ByteString.EMPTY;
            }
            return DaprCommonProtos.StateItem.newBuilder()
                    .setKey(it.getKey())
                    .setEtag(DaprCommonProtos.Etag.newBuilder().setValue(it.getEtag()).build())
                    .setValue(value)
                    .putAllMetadata(it.getMetadata())
                    .build();
        }).collect(Collectors.toList());
        DaprProtos.SetStateRequest request = DaprProtos.SetStateRequest
                .newBuilder()
                .setStoreName(storeName)
                .addAllStates(items)
                .build();
        return daprClient.setState(request);
    }

}
